<?php

namespace App\Http\Controllers;

use App\Article;
use App\Comment;
use App\Events\SolveProblem;
use App\Http\Requests;
use App\Link;
use App\Message;
use App\Parsedown;
use App\Permission;
use App\Solution;
use App\TaskLog;
use App\Solve;
use App\Study;
use App\Studycomment;
use App\Studyfav;
use App\Task;
use App\Timeline;
use App\User;
use App\Utils;
use Auth;
use Cookie;
use DB;
use Illuminate\Http\Request;
use Illuminate\Http\Response;
use Illuminate\Support\Facades\Event;
use Input;
use Log;
use Redirect;
use View;

class TasksController extends Controller
{
    /**
     * Display a listing of the resource.
     *
     * @return Response
     */
    public function __construct(Studyfav $studyfav)
    {
        $this->middleware('auth');
        $this->middleware('admin', ['only' => ['create', 'store', 'update', 'edit', 'move']]);
        $this->studyfav = $studyfav;
    }

    public function index()
    {
    }

    /**
     * Show the form for creating a new resource.
     *
     * @return Response
     */
    public function create()
    {
        //
        return view('tasks.create');
    }

    public function vote(Request $request)
    {
        $input = $request->all();
        $type = intval($input['type']);
        $vote_type = intval($input['vote_type']);

        if ($vote_type == 0) {
            $factor = 1;
        } else {
            $factor = -1;
        }

        $dataid = intval($input['dataid']);
        Log::info(var_export($input, true));
        $fav = $this->studyfav->getFavByUidSidType(Auth::user()->id, $dataid, $type);
        $entity = null;
        if ($type == 2) {
            //文章
            $entity = Article::find($dataid);
        } else if ($type == 1) {
            //讨论区
            $entity = Comment::find($dataid);
            $respons = Comment::whereTypeAndTaskidAndDelete(3, $entity->id, 0)->orderBy("created_at", "asc")->get();
            $commented = 0;
            foreach ($respons as $r) {
                if ($r->userid == Auth::user()->id && strlen($r->comment) >= 20) {
                    $commented = 1;
                }
            }
            if ($commented == 0 && $vote_type != 0) {
                return $entity->score;
            }
        }

        if (Auth::user()->id === $entity->userid) {
            return $entity->score;
        }
        $score = intval(Auth::user()->score / 100);
        if ($fav === null) {
//            not vote
            $fav = array();
            $fav['userid'] = Auth::user()->id;
            $fav['studyid'] = $dataid;
            $fav['type'] = $type;
            $fav['vote_type'] = $vote_type;
            Studyfav::create($fav);
            $entity->score = $entity->score + $factor * $score;
            if ($vote_type == 0) {
                $entity->vote += 1;
            } else {
                $entity->down_vote += 1;
            }
            $entity->save();
        } else {
            if ($fav->type >= 100) {
//                canceled vote
                $fav->type = $fav->type / 100;
                $fav->vote_type = $vote_type;
                $entity->score = $entity->score + $factor * $score;
                if ($vote_type == 0) {
                    $entity->vote += 1;
                } else {
                    $entity->down_vote += 1;
                }
            } else {
//                  voted
                if ($fav->vote_type == $vote_type) {
                    $fav->type = $fav->type * 100;
                    $entity->score = $entity->score - $factor * $score;
                    if ($vote_type == 0) {
                        $entity->vote -= 1;
                    } else {
                        $entity->down_vote -= 1;
                    }
                } else {
                    $fav->vote_type = $vote_type;
                    $entity->score = $entity->score + 2 * $factor * $score;
                    if ($vote_type == 0) {
                        $entity->vote += 1;
                        $entity->down_vote -= 1;
                    } else {
                        $entity->down_vote += 1;
                        $entity->vote -= 1;
                    }
                }
            }
            $fav->save();
            $entity->save();
        }
        return $entity->score;
    }

    public function solve(Request $request, $id)
    {
        $res = array();
        $res['success'] = false;
        $res['result'] = "";
        if ($request->isMethod('get')) {
            $res['result'] = "Woo 少年,你用的是get,我只接受post的请求哦mmd";
            return response()->json($res);
        }
        if ($id == 17) {
            if (strpos(($request->server('HTTP_REFERER')), "cpc.people.com.cn") == false) {
                $res['result'] = '对不起,你不是来自于我党官网[cpc.people.com.cn]的访客,你没有得到提交此题的授权!你现在来自于[' . $request->server('HTTP_REFERER') . ']';
                return response()->json($res);
            }
        }
        $task = Task::find($id);
        $user = Auth::user();
        $count = Solve::whereTaskidAndUserid($id, $user->id)->count();
        if ($count > 100 && $id != 139 && $id != 140 && $id != 142&&$id!=146) {
            $res['result'] = "你提交得太多了，请在参数列表中带上类似喜刷刷的验证码，使[" . Utils::id2url($id) . "+你的username+验证码+" . date("Ymd") . "]的md5的前27位都是0,参数名为 checkcode, 如果实在算不出来，请人肉联系qq 237660360";
            return response()->json($res);
        }

        $canswer = $task->answer;
        $answer = $request->all()["answer"];
        $answer = trim($answer);
        $solution = new Solution();
        $solution->solve($id, $answer, Auth::user()->name,Auth::user()->id,$request->all());
        if (($solution->can == true && $solution->res == true)
            || ($solution->can == false && $canswer == $answer)
        ) {
            //如果是最优化问题
            $cnt1 = Solve::whereTaskidAndTypeAndUserid($id, 0, $user->id)->count();
            $row = array();
            $row['userid'] = $user->id;
            $row['taskid'] = $id;
            $row['type'] = 0;
            $row['answer'] = $answer;
            if ($solution->res == true) $row['score'] = $solution->score;
            $data = Solve::create($row);

            //////////////

            $user = Auth::user();
            if ($cnt1 == 0) {
                Event::fire(new SolveProblem($user, $task, $answer));
            }


            /////////////

            $res['result'] = "恭喜你,答案正确";
            if ($solution->hint != "") {
                $res['result'] .= "<br><font color='red'>" . $solution->hint . "</font>";
            }
            $res['success'] = true;
        } else {
            $user = Auth::user();

            $row = array();
            $row['userid'] = $user->id;
            $row['taskid'] = $id;
            $row['type'] = 1;
            $row['answer'] = $answer;
            if ($solution->can == true)
                $row['score'] = $solution->score;
            $data = Solve::create($row);
            $res['result'] = "抱歉，答案错误";
            if ($solution->hint != "") $res['result'] .= "<br><font color='red'>" . $solution->hint . "</font>";
        }
        return response()->json($res);

    }

    public function contribute(Request $request, $id, $cid = 0)
    {

        if ($request->isMethod('post')) {
            $user = Auth::user();
            if ($request->all()['cid'] == '0') {
                $row = array();
                $row['userid'] = $user->id;
                $row['taskid'] = Utils::url2id($id);
                $row['content'] = $request->all()['text'];
                $row['username'] = $user->name;
                //type=2 未审核
                $row['type'] = 2;
                $data = Study::create($row);
            } else {
                $study = Study::find($request->all()['cid']);
                if ($study->userid != $user->id) {
                    echo "你没有修改的权限";
                    return;
                }
                $study->content = $request->all()['text'];
                $study->save();
            }
            if ($id == 0) return Redirect::to("/help")->with('message', '谢谢你的反馈,同时祝你早日修炼成为千里码^_^');
            else
                return Redirect::to('task/' . $id . '/learn#' . Utils::id2url($request->all()['cid']));
        }
        if ($cid != 0) {
            $cid = Utils::url2id($cid);
            $study = Study::find($cid);
        }
        $id = Utils::url2id($id);
        $task = Task::find($id);
        return View::make('projects.edit')
            ->with(compact('task'))
            ->with(compact('study'));
    }

    /**
     * Store a newly created resource in storage.
     *
     * @param  Request $request
     * @return Response
     */
    public function store(Request $request)
    {
        $input = $request->all();
        $email = Auth::user()['attributes']['email'];
        $input['author'] = $email;
        $Parsedown = new Parsedown();
        $input['content'] = $Parsedown->text($input['content']);
        // $input['material'] = $Parsedown->text($input['material']);
        $input['contributor'] = Auth::user()->id;
        $data = Task::create($input);
        $id = ($data["attributes"]["id"]);
        return Redirect::to('task/' . Utils::id2url($id));
        //
    }


    /**
     * Show the form for editing the specified resource.
     *
     * @param  int $id
     * @return Response
     */
    public function e(Request $request,$id)
    {
        //
        $id = Utils::url2id($id);
        $task = Task::find($id);
        $tl = Tasklog::whereTaskid($id)->orderby("created_at", "desc")->get()->first();
        $task->content = $tl['content'];
        return View::make('tasks.edit')->with(compact('task'));
    }

    /**
     * Update Task
     *
     * @param  Request $request
     * @param  int $id
     * @return Response
     */
    public function u(Request $request, $id)
    {
        //
        $input = $request->all();
        $task = Task::find($id);

        $data = array();
        $data['userid'] = Auth::user()->id;
        $data['content'] = $input['content'];
        $data['taskid'] = $id;
        Tasklog::create($data);
        $Parsedown = new Parsedown();
        $input['content'] = $Parsedown->text($input['content']);
        // $input['material'] = $Parsedown->text($input['material']);
        $task->title = $input['title'];
        $task->content = $input['content'];
        $task->answer = $input['answer'];
        $task->material = $input['material'];
        $task->study = $input['study'];
        $task->save();

        return Redirect::to('task/' . Utils::id2url($id));
    }

    public function comment(Request $request, $id)
    {
        $user = Auth::user();
        $input = $request->all();
        $row = array();
        $row['userid'] = $user->id;
        $row['taskid'] = $id;
        $row['comment'] = $input['comment'];
        $row['ruserid'] = 0;
        if (isset($input['reply'])) {
            $task = Task::find($id);
            Log::info($input['reply']);
            $ruser = User::wherename($input['reply'])->get()->first();
            $row['ruserid'] = $ruser->id;
            $data = Comment::create($row);
            $cid = $data['id'];
            $data = array();
            $data['senderid'] = 1;
            $ruser->msgcnt += 1;
            $ruser->save();
            $data['receiverid'] = $ruser->id;
            Log::info($input["reply"] . " " . $ruser->id);
            $Parsedown = new Parsedown();
            //$data['content']=$Parsedown->text($input['content']);
            $content = "**" . $user->name . "**在**" . $task['title'] . '**中回复了你的评论,<a target="_blank" href="/task/' . Utils::id2url($id) . "#comment" . $cid . '">点击查看</a>';
            $data['content'] = $Parsedown->text($content);
            Message::create($data);
        } else {
            $data = Comment::create($row);
        }
        return Redirect::to('task/' . Utils::id2url($id));
    }

    public function move(Request $request)
    {
        if ($request->isMethod('post')) {
            $input = $request->all();
            $task = Task::find($input['id']);
            $task->x = $input['x'];
            $task->y = $input['y'];
            $task->save();
        }
        return view('tasks.move');
    }

    public function moveTree(Request $request) {
        if ($request->isMethod('post')) {
            $input = $request->all();
            $ids = explode(',', $input['ids']);
            $xs = explode(',', $input['xs']);
            $ys = explode(',', $input['ys']);
            foreach ($ids as $i => $id) {
                $task = Task::find($id);
                $task->x = $xs[$i];
                $task->y = $ys[$i];
                $task->save();
            }
        }
        return "保存成功";
    }

    public function studycomment(Request $request)
    {
        $input = $request->all();
        Log::info($input);
        $arr = array();
        $arr['userid'] = Auth::user()->id;
        $arr['taskid'] = $input['cid'];
        $arr['comment'] = $input['comment'];
        Studycomment::create($arr);

        $data = array();
        $data['senderid'] = 1;
        $study = Study::find($input['cid']);
        $task = Task::find($study->taskid);
        $ruser = User::find($study->userid);
        $ruser->msgcnt += 1;
        $ruser->save();
        $data['receiverid'] = $ruser->id;
        $Parsedown = new Parsedown();
        //$data['content']=$Parsedown->text($input['content']);
        $content = "**" . Auth::user()->name . "**评论了**" . $task['title'] . '**中你的学习资料，<a target="_blank" href="/task/' . Utils::id2url($task->id) . "/learn#" . Utils::id2url($input['cid']) . '">点击查看</a>。';
        $data['content'] = $Parsedown->text($content);
        Message::create($data);

    }

    public function checkcontent()
    {
        if (!Permission::user_is_super(Auth::user())) return "无权限";

        $comments = DB::select('select * from comments where editor is null order by id desc limit 10');
        $Parsedown = new Parsedown();
        foreach ($comments as $comment) {
            $comment->title = "无";
            $comment->name = "无";
            $t1 = DB::select('select title from tasks where id=' . $comment->taskid);
            if (count($t1) > 0) $comment->title = $t1[0]->title;

            $t2 = DB::select('select name from users where id=' . $comment->userid);
            if (count($t2) > 0) $comment->username = $t2[0]->name;

            $comment->content = $Parsedown->text($comment->comment);
        }
        return View('tasks.checkcontent', compact('comments'));
    }

    public function setcontenttype(Request $request)
    {
        if (!Permission::user_is_super(Auth::user())) return "无权限";

        $input = $request->all();
        $jinghua = 0;
        if (array_key_exists("jinghua", $input)) {
            $jinghua = $input['jinghua'];
        }
        $data = DB::update('update comments set editor=' . $input['zeditor'] . ', jinghua=' . $jinghua . ' where id=' . $input['id']);
        return "该条内容已设为 " . 'zeditor:' . $input['zeditor'] . '  jinghua:' . $jinghua;
    }

    public function showlog(Request $request, $id)
    {
        $id = Utils::url2id($id);
        $tl = TaskLog::whereTaskid($id)->orderby("created_at", "desc")->firstOrFail();
        $c2 = $tl[0]->content;
        $c1 = $tl[1]->content;
        return View::make("tasks.diff")
            ->with(compact('c1'))
            ->with(compact('c2'));
    }


public function vote2(Request $request)
    {
        $input = $request->all();
        $type = intval($input['type']);
        $vote_type = intval($input['vote_type']);

        if ($vote_type == 0) {
            $factor = 1;
        } else {
            $factor = -1;
        }

        $dataid = Utils::url2id($input['dataid']);
        Log::info(var_export($input, true));
        $fav = $this->studyfav->getFavByUidSidType(Auth::user()->id, $dataid, $type);
        $entity = null;
        if ($type == 2) {
            //文章
            $entity = Article::find($dataid);
        } else if ($type == 1) {
            //讨论区
            $entity = Comment::find($dataid);
            $respons = Comment::whereTypeAndTaskidAndDelete(3, $entity->id, 0)->orderBy("created_at", "asc")->get();
            $commented = 0;
            foreach ($respons as $r) {
                if ($r->userid == Auth::user()->id && strlen($r->comment) >= 20) {
                    $commented = 1;
                }
            }
            if ($commented == 0 && $vote_type != 0) {
				$arr['score']=$entity->score;
				return response()->json($arr);
            }
        }

        if (Auth::user()->id === $entity->userid) {
			$arr['score']=$entity->score;
			return response()->json($arr);
        }
		$arr=array();
        $score = intval(Auth::user()->score / 100);
        if ($fav === null) {
//            not vote
            $fav = array();
            $fav['userid'] = Auth::user()->id;
            $fav['studyid'] = $dataid;
            $fav['type'] = $type;
            $fav['vote_type'] = $vote_type;
            Studyfav::create($fav);
            $entity->score = $entity->score + $factor * $score;
            if ($vote_type == 0) {
                $entity->vote += 1;
				$arr['fav']=1;
            } else {
                $entity->down_vote += 1;
				$arr['fav']=-1;
            }
            $entity->save();
        } else {
            if ($fav->type >= 100) {
//                canceled vote
                $fav->type = $fav->type / 100;
                $fav->vote_type = $vote_type;
                $entity->score = $entity->score + $factor * $score;
                if ($vote_type == 0) {
                    $entity->vote += 1;
					$arr['fav']=1;
				} else {
                    $entity->down_vote += 1;
					$arr['fav']=-1;
                }
            } else {
//                  voted
                if ($fav->vote_type == $vote_type) {
                    $fav->type = $fav->type * 100;
                    $entity->score = $entity->score - $factor * $score;
                    if ($vote_type == 0) {
                        $entity->vote -= 1;
						$arr['fav']=0;
                    } else {
                        $entity->down_vote -= 1;
						$arr['fav']=0;
                    }
                } else {
                    $fav->vote_type = $vote_type;
                    $entity->score = $entity->score + 2 * $factor * $score;
                    if ($vote_type == 0) {
                        $entity->vote += 1;
                        $entity->down_vote -= 1;
						$arr['fav']=1;
                    } else {
                        $entity->down_vote += 1;
                        $entity->vote -= 1;
						$arr['fav']=-1;
                    }
                }
            }
            $fav->save();
            $entity->save();
        }
		$arr['score']=$entity->score;
		return response()->json($arr);
    }

}
